/**
 * @author: Miss.杨
 * @date: 2025年1月11日 21:25:16
 * @description: 
 */
package com.sheepone.monitor.codec;

import java.nio.charset.StandardCharsets;
import java.util.List;

import com.sheepone.monitor.anno.ChannelHandlerOrder;
import com.sheepone.monitor.enums.SerializationAlgorithmsEnum;
import com.sheepone.monitor.enums.SheeponePackageSourceEnum;
import com.sheepone.monitor.enums.SheeponePackageTypeEnum;
import com.sheepone.webdev.log.WebDevLogger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

/**
 * @author: Miss.杨
 * @date: 2025年1月11日 21:25:16
 * @description:
 *               1、接收 byte[] 将其转化成 SheeponePackage
 *               2、接收 SheeponePackage 将其转化成 byte[]
 * 
 *               魔数（字符串类型，8个字节）："SHEEPONE"
 *               版本号：（0-127，1个字节）1.0
 *               序列化算法（0-127，1个字节）：0->json;1->protobuf;2->hessian
 *               来源服务（0-127，1个字节）：
 *               指令类型（0-127，1个字节）：
 *               请求序号（双工通信，提供异步能力）： TODO
 *               正文长度（int类型，4个字节）：
 *               消息正文：
 */
@ChannelHandlerOrder(Integer.MIN_VALUE)
public class SheeponeCodec extends ByteToMessageCodec<SheeponePackage> {
    private static byte[] MAGIC_NUMBER = "SHEEPONE".getBytes(StandardCharsets.UTF_8);
    private static byte VERSION = 1;
    private static byte SOURCE = SheeponePackageSourceEnum.MONITOR.getSource();

    private static WebDevLogger logger = WebDevLogger.getLogger(SheeponeCodec.class);

    /**
     * 将SheeponePackage编码成字节流
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, SheeponePackage msg, ByteBuf out) throws Exception {
        byte[] content = msg.getContent();
        out.writeBytes(MAGIC_NUMBER);
        out.writeByte(VERSION);
        out.writeByte(msg.getSerialization().getType());
        out.writeByte(SOURCE);
        out.writeByte(msg.getType().getType());
        out.writeInt(content.length);
        out.writeBytes(content);
    }

    /**
     * 将字节流解码成SheeponePackage
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 魔数
        byte[] magic = new byte[MAGIC_NUMBER.length];
        in.readBytes(magic, 0, MAGIC_NUMBER.length);
        // 版本
        byte version = in.readByte();
        // 序列化方法
        SerializationAlgorithmsEnum serialization = SerializationAlgorithmsEnum.convert(in.readByte());
        // 来源
        byte source = in.readByte();
        // 指令类型
        SheeponePackageTypeEnum type = SheeponePackageTypeEnum.convert(in.readByte());
        // 正文长度
        int length = in.readInt();
        // 消息正文
        byte[] content = new byte[length];
        in.readBytes(content, 0, length);
        SheeponePackage sheeponePackage = new SheeponePackage();
        sheeponePackage.setType(type);
        sheeponePackage.setSerialization(serialization);
        sheeponePackage.setContent(content);
        out.add(sheeponePackage);
        logger.debug("receive package for version:{} source:{} serialization:{} type:{} length:{}", version, source,
                serialization.getType(), type.getType(), length);
    }

}
